<template>
  <d2-container>
    <el-main>
      <!-- <div style="margin-bottom: 10px">学生姓名：{{courseOrder.student.name}}</div> -->

      <el-dialog title="退款" :visible.sync="showReimburse" style='position:fixed;left:30vw;width: 40vw;top:10vh;'>
              <p><b>退款金额不能大于订单金额</b></p>
              退款金额：<el-input placeholder="退款金额（元）" v-model="reimburseAmount" type='number' step='0.1' >
              </el-input>
             
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmReimburse">确认退款</el-button>
                <el-button type="secondary" @click="showReimburse = false">关闭</el-button>
              </div>
   </el-dialog>


      <el-row :span="12" style='background-color: #F6FAFE;height:40px;margin-top:10px;line-height: 40px;padding-left:10px;position: relative;'>
            <div style="font-size:18px;display: inline-block;">{{courseOrder.student.name}}</div>
            <div style="margin-left:3px;display: inline-block;font-size:15px">{{courseOrder.student.gender == 0 ? ' 男' : ' 女'}}</div>
            <div style="display: inline-block;margin-left: 10px;font-size:15px"> | <span style="margin-left:5px;background-color: red;display: inline-block;height:30px;width: 30px;text-align: center;position: relative;top:0px;line-height: 30px;color: rgb(96, 186, 178); border-color: rgb(96, 186, 178); background-color: rgb(221, 248, 239);border-style: solid;border-width: 1px;border-radius: 3px">课</span> 
            在读课程： {{courseCount}}</div>
            <div style="display: inline-block;margin-left: 10px;font-size:15px">| 
                <span style="margin-left:5px;background-color: red;display: inline-block;height:30px;width: 30px;text-align: center;position: relative;top:0px;line-height: 30px;color: rgb(153, 100, 245); border-color: rgb(188, 168, 255); background-color: rgba(188, 168, 255, 0.15);border-style: solid;border-width: 1px;border-radius: 3px">校</span>
            在读校区:  {{courseOrder.school.name}}</div>
            <div style="display: inline-block;margin-left: 10px;font-size:15px">| 
                <span style="margin-left:5px;background-color: red;display: inline-block;height:30px;width: 30px;text-align: center;position: relative;top:0px;line-height: 30px;color: rgb(52, 178, 211); border-color: rgb(96, 186, 178); background-color: rgb(182, 238, 251);border-style: solid;border-width: 1px;border-radius: 3px">联</span>
            联系方式： {{parentInfo}}</div>

            <div style="display: inline-block;float:right;font-size:15px" v-if='courseOrder.classStatus == 0'>
            <el-button @click='showReimburse = true'>退款</el-button>
          </div>
        </el-row>
        </el-row>


      <el-row :span="6" style="margin-top:10px;height:40px"><span style='width:2px;height:100%;background-color:rgb(52, 178, 211) ;color: rgb(52, 178, 211);margin-right: 3px'>_</span>采购课程
      </el-row>
      <el-row style='background-color:white;width: 100%;height:300px;position: relative;border-width: 1px;border-color: #D4DFE5;border-style: solid;margin-bottom:20px' >


            <div style="background-color:#F6FAFE;height:60px;width:100%;overflow: hidden;white-space: nowrap;">
                <div style="display: inline-block;font-size:15px;width: 300px"> <span style="margin-left:5px;background-color: red;display: inline-block;height:30px;width: 30px;text-align: center;position: relative;top:0px;line-height: 30px;color: rgb(96, 186, 178); border-color: rgb(96, 186, 178); background-color: rgb(221, 248, 239);border-style: solid;border-width: 1px;border-radius: 3px;margin-top:13px;margin-left: 15px">课</span> 
                    {{courseOrder.course.name}}
                    
                </div>
                <div style="display: inline-block;font-size:15px;width: 250px;">
                <span style="margin-left:5px;background-color: red;display: inline-block;height:30px;width: 30px;text-align: center;position: relative;top:0px;line-height: 30px;color: rgb(153, 100, 245); border-color: rgb(188, 168, 255); background-color: rgba(188, 168, 255, 0.15);border-style: solid;border-width: 1px;border-radius: 3px">校</span>
                {{courseOrder.school.name}}
                </div>

                <div style="display: inline-block;font-size:15px;width: 300px">
               <span style="margin-left:5px;background-color: red;display: inline-block;height:30px;width: 30px;text-align: center;position: relative;top:0px;line-height: 30px;color: rgb(52, 178, 211); border-color: rgb(96, 186, 178); background-color: rgb(182, 238, 251);border-style: solid;border-width: 1px;border-radius: 3px">班</span>

                <el-select v-model="courseOrder.class" filterable placeholder="搜索班级名称"   @click.native='classClick' style='margin-left:10px;' @change='classChange(index)' :disabled="true">
                    <el-option
                      v-for="item in courseOrder.courseOrderClassList"
                      :key="item._id"
                      :label="item.name + '  开班时间(' + item.startDateText + ')  授课老师(' + item.teacher + ')  剩余名额(' + (item.studentLimit - item.students) + ')'"
                      :value="item._id"
                    ></el-option>
                  </el-select>
                </div>

                <div style="display: inline-block;position: absolute;right:5px">
                   
                    <div style="display: inline-block;color:#98A0A7;position: absolute;right:265px;line-height: 60px;font-size: 14px">共：</div>

                    <div style="display: inline-block;position: absolute;right:223px;line-height: 60px;font-size: 20px;font-weight: 500;text-align: center;width: 50px">
                    {{courseOrder.numberTotal}}</div>
                    <div style="display: inline-block;color:#98A0A7;position: absolute;right:200px;line-height: 60px;font-size: 14px" v-if="courseOrder.type == 0">课时</div>

                    <div style="display: inline-block;color:#98A0A7;position: absolute;right:200px;line-height: 60px;font-size: 14px" v-if="courseOrder.type == 1">小时</div>

                    <div style="display: inline-block;color:#98A0A7;position: absolute;right:200px;line-height: 60px;font-size: 14px" v-if="courseOrder.type == 2">月</div>

                    <div style="display: inline-block;color:#98A0A7;position: absolute;right:140px;line-height: 60px;font-size: 14px">小计：</div>
                    <div style="display: inline-block;position: absolute;right:53px;line-height: 60px;font-size: 20px;font-weight: 500;text-align: center;width: 100px" >{{parseFloat(courseOrder.total - courseOrder.discount).toFixed(2)}}</div>
                    <div style="display: inline-block;color:#98A0A7;position: absolute;right:45px;line-height: 60px;font-size: 14px" >元</div>
                </div>

            
            </div>

             <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5">
            </div>

            <div style="width: 100%;position: relative;">
                <div style="position: relative;left:30px;top:20px;color:#98A0A7;display: inline-block;width: 100px">收费模式</div>
                <el-select v-model="courseOrder.type" filterable   style='display: inline-block;margin-left:10px;position: relative;;left:10px;top:20px;width: 150px' :disabled="true">
                    <el-option
                      v-for="item in courseOrder.pays"
                      :disabled="true"
                      :label="item.name"
                      :value="item.type"
                    ></el-option>
                  </el-select>
                <div style="position: relative;left:20px;top:20px;display: inline-block;width: 100px"> <i class="el-icon-close"></i></div>
                <el-input style="position: relative;left:-55px;top:20px;display: inline-block;width: 100px" v-model='courseOrder.numberTotal' @change="amountChange" type="number" min="0" :disabled="!edit">
                </el-input>
                <div style="position: relative;left:-40px;top:20px;display: inline-block;width: 120px"> = {{parseFloat(courseOrder.total).toFixed(2)}} 元</div>

                <div style="position: relative;left:33px;top:20px;color:#98A0A7;display: inline-block;width: 100px" v-if="courseOrder.type == 0">剩余课时</div>
                <div style="position: relative;left:33px;top:20px;color:#98A0A7;display: inline-block;width: 100px" v-if="courseOrder.type == 1">剩余小时</div>
                <div style="position: relative;left:33px;top:20px;color:#98A0A7;display: inline-block;width: 100px" v-if="courseOrder.type == 2">剩余月数</div>
                <el-input style="position: relative;left:30px;top:20px;display: inline-block;width: 100px" v-model='courseOrder.numberOfClasses'  type="number" min="0" :disabled="!edit" v-if="courseOrder.type == 0">
                </el-input>
                <el-input style="position: relative;left:30px;top:20px;display: inline-block;width: 100px" v-model='courseOrder.numberOfHours'  type="number" min="0" :disabled="!edit" v-if="courseOrder.type == 1">
                </el-input>
                <el-input style="position: relative;left:30px;top:20px;display: inline-block;width: 100px" v-model='courseOrder.numberOfMonths'  type="number" min="0" :disabled="!edit" v-if="courseOrder.type == 2">
                </el-input>

                <div style="position: absolute;right:200px;top:30px;color:#98A0A7;display: inline-block;width: 100px">付款方式</div>
                <el-select v-model="courseOrder.payWay"  style='display: inline-block;right:50px;position:absolute;margin-left:10px;top:20px;width: 150px' :disabled='!edit'>
                    <el-option
                      v-for="item in payTypes"
                      :label="item.name"
                      :value="item.value"
                      
                    ></el-option>
                  </el-select>

            </div>

             <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:40px">
            </div>



            <div style="width: 100%;position: relative;top:40px">
                <div style="position: relative;left:30px;top:20px;color:#98A0A7;display: inline-block;width: 100px">课程优惠</div>
                
                <el-input style="position: relative;left:20px;top:20px;display: inline-block;width: 100px" v-model='courseOrder.discount' type="number" min="0" @change='orderDiscountChange(index)' :disabled="!edit">
                    
                </el-input>
                <div style="position: relative;left:30px;top:20px;display: inline-block;width: 100px"> 元</div>

                <el-checkbox v-model="courseOrder.valid" style='display: inline-block;position: relative;top:20px;margin-left:15px;font-size: 18px' :disabled="!edit">有效期</el-checkbox>
                             <el-date-picker
                              v-model="courseOrder.validDate"
                              type="date"
                              placeholder="截止有效期"
                              :disabled="((!courseOrder.valid) || (!edit))"
                              style='position: relative;top:20px;left:10px;width: 150px'

                      ></el-date-picker>
                
                <div style="display: inline-block;" v-if='courseOrder.type ==2' >
                    <div style="position: relative;left:50px;top:20px;color:#98A0A7;display: inline-block;width: 100px" >开始月份</div>
                     <el-date-picker
                          v-model="courseOrder.startDate"
                          type="month"
                          placeholder="开始月份"
                          style='position: relative;top:20px;left:40px;width: 150px'
                          :disabled="!edit"
                  ></el-date-picker>
                </div>

                <div style="position: absolute;right:200px;top:30px;color:#98A0A7;display: inline-block;width: 100px">订单类型</div>
                <el-select v-model="courseOrder.bonusType"  style='display: inline-block;right:50px;position:absolute;margin-left:10px;top:20px;width: 150px' :disabled='!edit'>
                    <el-option
                      v-for="item in bonusTypes"
                      :label="item.name"
                      :value="item.value"
                      
                    ></el-option>
                  </el-select>
            </div>
 

            <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:80px">
            </div>

             <div style="width: 100%;position: relative;top:40px">
               
            </div>

             <div style="position: relative;left:30px;top:100px;color:#98A0A7;display: inline-block;width: 100px">对内备注</div>
                
                <el-input style="position: relative;left:20px;top:100px;display: inline-block;width: 40%" v-model='courseOrder.memoIn' placeholder='内部人员可见' :disabled="!edit">
                    
                </el-input>

                <div style="position: relative;left:30px;top:100px;color:#98A0A7;display: inline-block;width: 100px">对外备注</div>
                
                <el-input style="position: relative;left:20px;top:100px;display: inline-block;width: 40%" v-model='courseOrder.memoOut' placeholder='订单打印可见' :disabled="!edit">
                    
                </el-input>

            </div>


        </el-row>

        <el-row :span="6" style="margin-top:10px;height:40px"><span style='width:2px;height:100%;background-color:rgb(52, 178, 211) ;color: rgb(52, 178, 211);margin-right: 3px'>_</span>
          提成信息
          <el-button @click="showStaff = true" type='primary' style='height:30px;position: relative;top:0px;font-size: 14px;padding: 5px;margin-left:50px;display: inline-block;' :disabled='!edit'>添加提成人员
          </el-button>
      </el-row>

          
           <el-row v-if="courseOrder.bonus.length == 0" style='background-color: white;height:150px;margin-top: 10px;border-width: 1px;border-color: #D4DFE5;border-style: solid;'>
            <div style="color:#CACBCC;width: 100%;text-align: center;line-height: 150px;height: 150px">
              <el-button type='primary' @click='showStaff = true' :disabled="!edit">添加提成人员</el-button>
            </div>
        </el-row>

            <el-row style='background-color:white;width: 100%;position: relative;border-width: 1px;border-color: #D4DFE5;border-style: solid;margin-bottom:20px;margin-top: 10px;border-width: 1px;border-color: #D4DFE5;border-style: solid;'  v-else>
            
            </div>

             <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5">
            </div>

            <div style="width: 100%;position: relative;">
                <div v-for='(commission,index) in courseOrder.bonus' style="margin-bottom:10px;height:60px;position: relative;">
                    <div style="position: relative;left:30px;display: inline-block;width: 100px;height: 60px">{{commission.staff.name}}</div>
                    <!-- <div style="position: relative;left:80px;color:#98A0A7;display: inline-block;width: 100px;height: 60px;line-height: 60px">提成类型：</div>
                    <el-select v-model="commission.type"  style='display: inline-block;left:255px;position:absolute;top:15px;width: 150px' :disabled='!edit'>
                    <el-option
                      v-for="item in bonusTypes"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select> -->
                  <div style="display: inline-block;">
                    <div style="width: 70px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:150px;color:#98A0A7;">百分比:</div>
                    <el-input style="position: relative;width: 100px;left:150px;display: inline-block;" v-model='commission.percentage' :disabled='!edit' @change='commissionChange(index)' type='number'> </el-input>
                  </div>
                  <div style="display: inline-block;">
                    <div style="width: 60px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:300px;color:#98A0A7;">提成:</div>
                        <el-input style="position: relative;width: 100px;display: inline-block;left:300px " v-model='commission.commission' :disabled='true'> </el-input>
                  </div>
                  <div style="display: inline-block;">
                    <div style="width: 60px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:400px;color:#98A0A7;">备注:</div>
                        <el-input style="position: relative;width: 200px;display: inline-block;left:400px " v-model='commission.memo' :disabled="!edit"> </el-input>
                  </div>
                    <button style="height:30px;width: 30px;background-color: #F6E4E7;border-style: solid;border-width: 1px;border-color: #FB6363;border-radius: 3px;position: absolute;top:20px;right:50px" @click="removeCommission(index)"><i class="el-icon-close" style="color: #FB6363;" :disabled="!edit"></i> 
                    </button>
                  <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:-9px"></div>
                </div>
            </div>

             <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:40px">
            </div>

        </el-row>
          <div style="width: 100%;background-color: white;position: relative;height: 60px">
              <div style="width: 100%;position: relative;height: 1px;background-color: #D4DFE5;top:0px"></div>
              <div style="width: 100px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:20px;color:#98A0A7;">单课均价 : </div>
              <div style="width: 100px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:10px;font-size: 20px;text-align: center">{{parseFloat(courseOrder.averagePrice).toFixed(2)}}</div>
              <div style="width: 100px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:0px;color:#98A0A7;">元 / 课</div>

              <div style="width: 100px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:20px;color:#98A0A7;">单小时均价 : </div>
              <div style="width: 100px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:10px;font-size: 20px;text-align: center">{{parseFloat(courseOrder.averagePriceHour).toFixed(2)}}</div>
              <div style="width: 100px;display: inline-block;position: relative;top:0;height: 60px;line-height: 60px;left:0px;color:#98A0A7;">元 / 小时</div>

          </div>

      </el-main>
    <el-footer>
          <el-button type="primary" @click="submit" :disabled="!edit">提交</el-button>
          <el-button @click='edit = true'>修改</el-button>


    </el-footer>

                    <el-dialog title="员工" :visible.sync="showStaff" >
                        <el-input placeholder="请输入员工姓名" v-model="search.staffName" size="small">
                            <el-button slot="append" icon="el-icon-search" @click="searchStaff"></el-button>
                        </el-input>
                        <el-table :data="staffList" height="500">
                            <el-table-column property="name" label="员工姓名"></el-table-column>
                            <el-table-column  label="操作">
                                <template slot-scope="scope">
                                    <el-button @click="addStaff(scope.$index)" type="text">选择</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="showStaff = false">确认</el-button>
                        </div>
                    </el-dialog>

  </d2-container>
</template>


<script>
// import { request } from "http";
import request from "@/plugin/axios";
import {mapState} from "vuex";
export default {
  data() {
    return {

      courseOrder:{student:{name:''},course:{name:''},school:{name:''},bonus:[]},
      student:undefined,
      price:undefined,
      memoIn:undefined,
      memoOut:undefined,
      payWay:undefined,
      payStatus:undefined,
      edit:false,
      search :{
        class:undefined,
        staffName : undefined
      },
      showStaff : false,
      parentInfo : '',
      classList : [],
      staffList:[],
      bonusTypes : [{value:0,name:'新生'},{value:1,name:'试听'},{value:2,name:'转介绍'},{value:3,name:'续报'},{value:4,name:'接待'},{value:6,name:'转课'},{value:-1,name:'批量导入'}],
      payTypes : [{value:0,name:'现金'},{value:1,name:'银行卡'},{value:2,name:'微信'},{value:3,name:'支付宝'},{value:4,name:'其他'}],
      courseCount : 0,
      reimburseAmount : 0,
      showReimburse :false

    };
  },
  computed: {
            ...mapState('d2admin/user', ['info']),
        },
  methods: {


    getCourseOrderOne(id) {
      request({
        url: "/courseOrder/getCourseOrderOne",
        method: "post",
        data: {_id: id}
      }).then(res => {
        if (res.code == 200) {
          if (res.data) {
            // this.student = res.data.student.name;
            this.courseOrder = res.data;
            // this.memoIn = res.data.memoIn;
            // this.memoOut = res.data.memoOut;
            if (this.courseOrder.type == 0){
              this.courseOrder.typeText = '课时'
            }
            if (this.courseOrder.type == 1){
              this.courseOrder.typeText = '小时'
            }
            if (this.courseOrder.type == 2){
              this.courseOrder.typeText = '月'
            }

            this.courseOrder.valid = res.data.valid == 1 ? true : false

            this.courseOrder.pays = [{type:0,name:'1课时=' + this.courseOrder.course.pricePerClass + '元',price:this.courseOrder.course.pricePerClass},{type:1,name:'1小时=' + this.courseOrder.course.pricePerHour+ '元',price:this.courseOrder.course.pricePerHour},{type:2,name:'1个月=' + this.courseOrder.course.pricePerMonth+ '元',price:this.courseOrder.course.pricePerMonth}]
            if (this.courseOrder.averagePrice == undefined){
              let temp = 0
              temp = this.courseOrder.total + (this.courseOrder.leftTotal || 0)

              temp = temp - this.courseOrder.discount

              for (var i = 0 ; i < this.courseOrder.bonus.length ; i++){
                temp -= this.courseOrder.bonus[i].commission
              }

              if (this.courseOrder.type ==2 ){
                this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal / 4 * 100) / 100
              }
              else if (this.courseOrder.type == 1){
                this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * this.courseOrder.course.duration * 100) / 100
              }
              else{
                this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * 100) / 100
              }
            }

            if (this.courseOrder.averagePriceHour == undefined){
              let temp = this.courseOrder.total - this.courseOrder.discount + (this.courseOrder.leftTotal || 0)

              for (var i = 0 ; i < this.courseOrder.bonus.length ; i++){
                temp -= this.courseOrder.bonus[i].commission
              }

              if (this.courseOrder.type ==2 ){
                this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / 4 / this.courseOrder.course.duration * 100) / 100
              }
              else if (this.courseOrder.type == 1){
                this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal * 100) / 100
              }
              else{
                this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / this.courseOrder.course.duration * 100) / 100
              }
            }
            
            this.search.class = this.courseOrder.class == null ? undefined : this.courseOrder.class._id


            if (this.search.class != undefined){
              this.searchClass()
            }

            request({
                    url: "/parent/getParentsByStudent",
                    method: "post",
                    data : {student:this.courseOrder.student._id}
                  }).then(res => {
                    let temp = ''
                    for (var i = 0 ; i < res.data.length ; i++){
                        temp += res.data[i].cellphone + ' (' + res.data[i].name + ' ' + res.data[i].relation + ')'
                        if (i != res.data.length - 1){
                            temp += ', '
                        }
                    }
                    this.parentInfo = temp
                    // 返回数据
                  });

                request({
                    url: "/courseorder/getStudentCourseOrder",
                    method: "post",
                    data : {student:this.courseOrder.student._id,classStatus:0}
                  }).then(res => {
                    this.courseCount = new Set(res.data.courseOrder.map(function(e){return e.course._id})).size
                    // 返回数据
                  });
            
          }
        }
      })
    },


    amountChange(){

                let amount = this.courseOrder.numberTotal - (this.courseOrder.leftAmount || 0)
                if (this.courseOrder.type == 0){

                    this.courseOrder.total = parseFloat(amount * parseFloat(this.courseOrder.course.pricePerClass)).toFixed(2)
                }
                else if (this.courseOrder.type == 1){
                    this.courseOrder.total = parseFloat(amount * parseFloat(this.courseOrder.course.pricePerHour)).toFixed(2)
                }
                else if (this.courseOrder.type == 2){
                    this.courseOrder.total = parseFloat(amount * parseFloat(this.courseOrder.course.pricePerMonth)).toFixed(2)
                }
                let temp = this.courseOrder.total - this.courseOrder.discount + (this.courseOrder.leftTotal || 0 )

                console.log(temp,amount,'okok')
                
                for (var i = 0 ; i < this.courseOrder.bonus.length ; i++){
                    this.courseOrder.bonus[i].commission = (this.courseOrder.total - this.courseOrder.discount) *  this.courseOrder.bonus[i].percentage / 100
                  
                    temp -= this.courseOrder.bonus[i].commission
                }

              if (this.courseOrder.type ==2 ){
                this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal / 4 * 100) / 100
                this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / 4 / this.courseOrder.course.duration * 100) / 100

              }
              else if (this.courseOrder.type == 1){
                this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * this.courseOrder.course.duration * 100) / 100
                this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal * 100) / 100

              }
              else{
                this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * 100) / 100
                this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / this.courseOrder.course.duration * 100) / 100
              }

                // let total = 0
                //     total += this.courseOrder.total - this.courseOrder.discount
                // this.courseTotal = total
            },

      searchClass(){
                request({
                    url: "/class/getClassList",
                    method: "post",
                    data: {
                        page: 1,
                        pageSize: 99999999,
                        name: this.search.class,
                        school: [this.school]
                    }
                }).then(res => {
                    if (res.code == 200) {
                        this.classList = res.data.class
                         
                        let temp = []
                        for (var i = 0 ;i < res.data.class.length ;i++) {
                            let data = {}
                            data._id = res.data.class[i]._id
                            data.name = res.data.class[i].name
                            data.teacher = res.data.class[i].teacher == null ? '暂无' : res.data.class[i].teacher.name
                            data.startDateText = formatTime.formatDate(res.data.class[i].startDate)
                            data.studentLimit = res.data.class[i].studentLimit
                            data.students = res.data.class[i].student.length
                            temp.push(data)
                        }
                        this.courseOrder.courseOrderClassList = temp
                        this.courseOrder.courseOrderClassList.push('')
                        this.courseOrder.courseOrderClassList.splice(this.courseOrder.courseOrderClassList.length-1, 1)

                    }
                });
            },
      classClick(){
                request({
                    url: "/class/getClassList",
                    method: "post",
                    data: {
                        page: 1,
                        pageSize: 99999999,
                        // name: this.search.class,
                        school: [this.school],
                        course: this.courseOrder.course._id
                    }
                }).then(res => {
                    if (res.code == 200) {
                        
                        let temp = []
                        for (var i = 0 ;i < res.data.class.length ;i++) {
                            let data = {}
                            data._id = res.data.class[i]._id
                            data.name = res.data.class[i].name
                            data.teacher = res.data.class[i].teacher == null ? '暂无' : res.data.class[i].teacher.name
                            data.startDateText = formatTime.formatDate(res.data.class[i].startDate)
                            data.studentLimit = res.data.class[i].studentLimit
                            data.students = res.data.class[i].student.length
                            temp.push(data)
                        }
                        this.courseOrder.courseOrderClassList = temp
                         this.courseOrder.courseOrderClassList.push({})
                         this.courseOrder.courseOrderClassList.splice(this.courseOrder.courseOrderClassList.length-1, 1)
                    }
                });
      
  },

  orderDiscountChange(){
      let temp = this.courseOrder.total - this.courseOrder.discount + (this.courseOrder.leftTotal || 0)

      for (var i = 0 ; i < this.courseOrder.bonus.length ; i++){
        temp -= this.courseOrder.bonus[i].commission
      }


    if (this.courseOrder.type ==2 ){
      this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal / 4 * 100) / 100
      this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / 4 / this.courseOrder.course.duration * 100) / 100

    }
    else if (this.courseOrder.type == 1){
      this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * this.courseOrder.course.duration * 100) / 100
      this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal * 100) / 100

    }
    else{
      this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * 100) / 100
      this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / this.courseOrder.course.duration * 100) / 100
    }


  },

  commissionChange(index){
    // if (this.courseOrder.bonus[index]._id != undefined){
    //   //confirm change
    // }
    // else{

    // }

    let amount = this.courseOrder.numberTotal - (this.courseOrder.leftAmount || 0)

    this.courseOrder.bonus[index].commission = Math.round((this.courseOrder.total - this.courseOrder.discount) *  this.courseOrder.bonus[index].percentage) / 100

    let temp = 0
    if (this.courseOrder.type == 0){
                                temp = amount * parseFloat(this.courseOrder.course.pricePerClass)
                              }
                              else if (this.courseOrder.type == 1){
                                temp = amount * parseFloat(this.courseOrder.course.pricePerHour)
                              }
                              else{
                                 temp = amount * parseFloat(this.courseOrder.course.pricePerMonth)
    }

    temp = temp + (this.courseOrder.leftTotal || 0) - this.courseOrder.discount

    for (var i = 0 ; i < this.courseOrder.bonus.length ; i++){
      temp -= this.courseOrder.bonus[i].commission
    }
    if (this.courseOrder.type ==2 ){
      this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal / 4 * 100) / 100
      this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / 4 / this.courseOrder.course.duration * 100) / 100

    }
    else if (this.courseOrder.type == 1){
      this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * this.courseOrder.course.duration * 100) / 100
      this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal * 100) / 100

    }
    else{
      this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * 100) / 100
      this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / this.courseOrder.course.duration * 100) / 100
    }

    if (this.courseOrder.bonus[index]._id != undefined){
      this.courseOrder.bonus[index].modified = true
    }

  },
  removeCommission(index){
    if (this.courseOrder.bonus[index]._id != undefined){
      //confirm delte this commission
      this.$confirm('如果已经发放提成，请联系相关人员进行下一步操作','需要删除该提成吗？',{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then((value) => {
                request({
                    url: "/staffCommission/removeStaffCommission",
                    method: "post",
                    data: {id:this.courseOrder.bonus[index]._id,orderid:this.courseOrder._id}
                }).then(res => {
                    if (res.code == 200){
                      this.$alert('','删除成功',{
                                confirmButtonText :'确定',
                                type: 'info'
                            }).then((value) =>{
                              this.courseOrder.bonus.splice(index,1)
                              let temp = 0
                              let amount = this.courseOrder.numberTotal - (this.courseOrder.leftAmount || 0)
                              if (this.courseOrder.type == 0){
                                temp = amount * parseFloat(this.courseOrder.course.pricePerClass)
                              }
                              else if (this.courseOrder.type == 1){
                                temp =amount * parseFloat(this.courseOrder.course.pricePerHour)
                              }
                              else{
                                 temp = amount * parseFloat(this.courseOrder.course.pricePerMonth)
                              }
                              temp = temp - this.courseOrder.discount + (this.courseOrder.leftTotal || 0)

                                  for (var i = 0 ; i < this.courseOrder.bonus.length ; i++){
                                    temp -= this.courseOrder.bonus[i].commission
                                  }

                                  if (this.courseOrder.type ==2 ){
                                    this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal / 4 * 100) / 100
                                    this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / 4 / this.courseOrder.course.duration * 100) / 100

                                  }
                                  else if (this.courseOrder.type == 1){
                                    this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * this.courseOrder.course.duration * 100) / 100
                                    this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal * 100) / 100

                                  }
                                  else{
                                    this.courseOrder.averagePrice = Math.round(temp / this.courseOrder.numberTotal * 100) / 100
                                    this.courseOrder.averagePriceHour = Math.round(temp / this.courseOrder.numberTotal / this.courseOrder.course.duration * 100) / 100
                                  }

    


                            })
                    }
                });
        })
        .catch(()=>{
          // this.getCourseOrderOne(this.id)
        })

    }
    else{
      this.courseOrder.bonus.splice(index,1)
    }
  },
  addStaff(index){
    this.courseOrder.bonus.push(
      {
        staff : this.staffList[index],
        percentage : 0,
        commission : 0,
        type : this.courseOrder.bonusType,
        memo : ''
      }
    )
  },

  
  searchStaff() {

                request({
                    url: "/staff/getStaffList",
                    method: "post",
                    data: {
                        page: 1,
                        pageSize: 100,
                        name: this.search.staffName,
                        school: this.school
                    }
                }).then(res => {
                    this.staffList = res.data.staff;
                    this.searchStaffCount = res.data.count;
                });
            },
            confirmReimburse (){
              if (this.reimburseAmount > this.courseOrder.total){
                this.$alert('退款金额不能大于总金额')
                return
              }
              this.$confirm('退款金额为' + this.reimburseAmount + '元。退款后，该课程余额清零。','确认要退款吗？',{}).then(()=>{
              request({
                    url: "/courseOrder/reimburseCourseOne",
                    method: "post",
                    data: {
                       id : this.id,
                       amount : this.reimburseAmount
                    }
                }).then(res => {
                    if (res.code == 200){
                      this.$message('退款成功！')
                      this.showReimburse = false
                      this.getCourseOrderOne(this.id)
                    }

                });
            }).catch(()=>{

            })

            },

    submit(){
      var i = 0;
      var message = ''
      while (i < this.courseOrder.bonus.length){
        if (this.courseOrder.bonus[i].percentage <= 0){
          this.$alert('','提成不能为0',{
                      confirmButtonText: "确定"
                    })
          return false
          }
          else if (this.courseOrder.bonus[i].modified){
            message = '1'
            i += 1
          }
          else{
            i += 1
          }
        }

      if (message.length > 0){
        this.$confirm('如果确认，已经创建的提成数据会被修改，如果已经发放提成，请联系相关人员下一步操作。','有提成数据发生修改，需要继续吗？',{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then((value) => {
                request({
                    url: "/courseOrder/updateCourseOrder",
                    method: "post",
                    data: {data:this.courseOrder}
                }).then(res => {
                    if (res.code == 200){
                      this.$alert('','订单修改成功！',{
                                confirmButtonText :'确定',
                                type: 'info'
                            }).then((value) =>{
                              this.refresh = true
                              this.$router.back(-1)
                              
                              
                            })
                    }
                });
        })
        .catch(()=>{
          this.getCourseOrderOne(this.id)
        })
      }
      else{
        request({
                    url: "/courseOrder/updateCourseOrder",
                    method: "post",
                    data: {data:this.courseOrder}
                }).then(res => {
                    if (res.code == 200){
                      this.$alert('','订单修改成功！',{
                                confirmButtonText :'确定',
                                type: 'info'
                            }).then((value) =>{
                              this.refresh = true
                              this.$router.back(-1)
                               
                            })
                    }
                });
      }
      // update order
      // first update order itself , second generate commission



}
},
  beforeRouteLeave(to,from,next){
    if (this.refresh){
      to.meta.refresh = 'a'
      this.refresh = undefined
    }
    next()
  },

  created() {
    this.school = this.info.school[0]._id
                       this.agent = this.info.staff == undefined ? null : this.info.staff._id
            this.staffname = this.info.staff == undefined ? '' : this.info.staff.name
    if (this.$route.query.id != undefined) {
      this.getCourseOrderOne(this.$route.query.id)
      this.id = this.$route.query.id
    }
  }
}
</script>
